package main

import (
	"fmt"
	"path/filepath"
	"regexp"
	"strconv"
	"strings"
)

func regepTest() {
	pos := strings.Split("447-210", "-")
	fmt.Println("分割为split", pos)
	
	if strings.Contains("linekey=123", "key") {
		fmt.Println("找到key为：", "linekey=123")
	} else {
		fmt.Println("未找到key")
	}
	
	mainName := "吉宁abcd"
	mainExt := ".tga"
	name := "吉宁abcd1234.tga"
	
	trimPrefixStr := strings.TrimPrefix(name, mainName)
	trimSuffixStr := strings.TrimSuffix(trimPrefixStr, mainExt)
	fmt.Println("去前缀后缀为:", trimSuffixStr)
	
	nameL := len(name)
	mainNameL := len(mainName)
	
	tempStr := name[mainNameL:]
	tempStrL := len(tempStr)
	
	fileTypeSuffixL := len(mainExt)
	
	if nameL > mainNameL && nameL > fileTypeSuffixL {
		resultStr := tempStr[:tempStrL-fileTypeSuffixL]
		
		fmt.Println("截取尾部为:", resultStr)
		resultMatch := regexp.MustCompile(`^\d{4}$`)
		if resultMatch.MatchString(resultStr) {
			fmt.Println("匹配成功")
		} else {
			fmt.Println("匹配失败")
		}
	}
	
	//strings.ReplaceAll("zxc.txt", ".txt", "   ")
	//newStr := tempStr.replace
}

func main() {
	regepTest()
	
	//如果某个片段包含了当前目录（.）或上级目录（..），它会处理这些特殊标记来构建最终的路径。
	path := filepath.Join("project", ".", "src", "..", "main.go")
	fmt.Println("path->path:", path)
	
	// string to []byte
	s1 := "hello"
	b := []byte(s1)
	
	// []byte to string
	s2 := string(b)
	fmt.Println("s2->值:", s2)
	
	//extTest()
	
	fillTest("abc.doc,今天,明天,大运河马拉松")
	
	myint := ToInt(7.31)
	fmt.Println("数据类型转换->convert:", myint)
	
	//疑问：这里注意TrimSuffix的含义
	var s = "¡¡¡Hello, Gophers!!!.txt。text"
	s = strings.TrimSuffix(s, "ext")
	//s = strings.TrimSuffix(s, ", Marmots!!!")
	fmt.Print(s, "\r")
	
	//疑问：这里注意filepath.Base的含义
	var mainName, mainExt string
	detailExt := "A:/home/abcde0002.tga"
	mainExt = filepath.Ext(detailExt)
	mainName = strings.TrimSuffix(filepath.Base(detailExt), mainExt)
	
	fileBase := filepath.Base(detailExt)
	fmt.Println("fileBase为:", fileBase, "mainExt为:", mainExt, "mainName为:", mainName)
	//fmt.Println(filepath.Base("A:/home/abcd.tga"))
	
	//判断前缀
	strhasPrefix := strings.HasPrefix(filepath.Base(detailExt), mainName)
	fmt.Println("是否有前缀：", strhasPrefix, "\n")
	
	strhasSuffix := strings.HasSuffix(fileBase, mainExt)
	fmt.Println("是否有后缀：", strhasSuffix)
	
	StrIndexTest()
	
	strIndexMoreTest()
	//extTest()
	//appendOne()
	//appendTwo()
	//appendThree()
	//absolutePath()
	//relativePath()
	
	/*
		//字符串切片处理
		//Fields() 函数、 Split()函数
		var str string = "abc def ghi"
		//Fields函数默认识别的符号是空格
		result1 := strings.Fields(str)
		fmt.Println("result1:",result1)
		fmt.Printf("result1->Type:%T",result1)
	
	
		var str2 string = "abc,def,gh,i"
		//识别逗号分隔
		result2 := strings.Split(str2, ",")
		fmt.Printf("\nresult2->:%v",result2)
	
		//因为fields()函数默认只能识别空格，不能识别其他符号，
		// 而Split()函数则均可以识别把切片按指定分隔符进行转换成字符串
	
		//join()函数
		var slice = []string{"123", "456", "789"}
		//切片转换成字符串
		resultJoin := strings.Join(slice,":")
		fmt.Println("resultJoin:= ",resultJoin)
	*/
	
	/*
		//数据处理: 使用strconv.Itoa()函数将数值转换成字符串
		var num int = 12345678
		resultNumStr := strconv.Itoa(num)
		fmt.Printf("resultNumStr->Type:%T", resultNumStr)
		fmt.Println("\nString:=", resultNumStr)
	
		//sprintf() 将整数转换成字符串
		fmt.Printf("初始数据类型: %T\n", num)
		resultPrintf := fmt.Sprintf("%d", num)
		fmt.Printf("resultPrintf->Type:%T", resultPrintf)
		fmt.Println("\nresultPrintf:=", resultPrintf)
	
		//使用strconv.Atoi()
		// var numStr string = "123456789"
		var numStr string = "abc" //"abc"无法转换成整数，所以抛出异常
		result, err := strconv.Atoi(numStr)
		if err == nil {
			fmt.Printf("result->Type:%T\n", result)
		} else {
			fmt.Println(err)
		}
	*/
	
	//布尔值
	//Go语言中不允许将整型强制转换为布尔型
	//布尔型无法参与数值运算，也无法与其他类型进行转换。
	
	/*
			var (
		        // url  string
		        // path string
		        a = "abbaabcddccd"
		        myStr = "cd"
		    )
	
		    str := urlProcess("http://www.jb51.net/article/245112.html")
		    fmt.Println("URL:= ",str)
	
		    anotheStr := pathProcess("http://www.jb51.net")
		    fmt.Println("anotheStrURL:= ",anotheStr)
	
		    //Index()函数判断出现在前面的位置
		    head := strings.Index(a, myStr)
	
		    //LastIndex()函数判断出现在末尾的位置
		    tail := strings.LastIndex(a, myStr)
		    fmt.Printf("首次出现的位置:= %d\n最后出现的位置:= %d\n",head,tail)
	
			//替换
			result := strings.Replace(a, "cd", "CD", -1)
			fmt.Println("替换a:=",a,"\n替换后result:= ",result)
	
			//统计次数
			count := strings.Count(a,"ab")
			fmt.Printf("count: %+v\n", count)
			//如果希望显示一些详情，可和 %+v 格式化符号配合。
	
			//重复
			var someStr = "加油~"
			resultOne := strings.Repeat(someStr,3)
			fmt.Printf("Repeat: %+v\n", resultOne)
	
			//大小写
			resultTwo := strings.ToUpper(a)
			fmt.Println("resultTwo:= ",resultTwo)
	
			//把上面转换的大写给转成小写
			resultThird := strings.ToLower(resultTwo)
			fmt.Printf("小写: %v\n", resultThird)
	*/
	
	/*
		//TrimSpace() 只能去除首尾空白字符,字符串中间的空白无法去除
		var tempFour = " aabcc  "
		resultFour := strings.TrimSpace(tempFour)
		fmt.Println("去空白:=", resultFour, "\n长度:= ", len(resultFour))
	
		//Trim() 去除指定位置字符
		var tempFive = "this A is test 啊web -this- 说明啊web"
		resultFive := strings.Trim(tempFive, "web")
		fmt.Println("尾部去除5:", resultFive)
	
		//从左往右删除所有指定的字符，直到遇到不包含在指定的字符为止
		resultSix := strings.TrimLeft(tempFive, "this")
		fmt.Println("TrimLeft去除6:", resultSix)
	
		//空格也需匹配删除，直到没有指定的字符可以匹配为止
		resultSeven := strings.TrimLeft(tempFive, "this ")
		fmt.Println("TrimLeft去除7:", resultSeven)
	
		//从右往左删除所有指定的字符，直到遇到不包含在内的字符为止
		resultEight := strings.TrimRight(tempFive, "web")
		fmt.Println("TrimLeft去除8:", resultEight)
	*/
	
	/*
		    fmt.Println("请输入URL和路径:")
		    fmt.Scanf("%s%s", &url, &path)
			fmt.Printf("URL: %s\n", urlProcess(url))
		    // fmt.Printf("路径: %s", pathProcess(path))
	*/
}

func strIndexMoreTest() {
	idx := strings.Index("1224vasdf=13fd", "=")
	fmt.Println("找索引index为:", idx)
}

// 数据转换
func ToInt(i interface{}) int {
	//log.Println(i, reflect.TypeOf(i))
	switch i.(type) {
	case int:
		return i.(int)
	case float64:
		return int(i.(float64))
	case string:
		bb, err := strconv.ParseInt(i.(string), 10, 64)
		if err == nil {
			return int(bb)
		}
	default:
	}
	return 0
}

func fillTest(someStr string) {
	pris := []string{}
	if s := strings.TrimRight(someStr, ","); s != "" {
		pris = strings.Split(s, ",")
	}
	fmt.Println("pris处理后：", pris)
}

func StrIndexTest() {
	out := "Xrender Info:{\"status\":1,\"msg\":[{\"code\":10001,\"en\":\"missing Files:\\r\\nC:\\\\Users\\\\xp000025768\\\\}]"
	idx2 := strings.Index(out, "Info:")
	fmt.Println("索引为：", idx2)
}

func filePathBaseTest() {
	fmt.Println("/home/gfg filepath.Base后为:", filepath.Base("/home/gfg"))
	fmt.Println(".gfg filepath.Base后为:", filepath.Base(".gfg"))
	fmt.Println("/gfg filepath.Base后为:", filepath.Base("/gfg"))
	fmt.Println(":gfg/GFG filepath.Base后为:", filepath.Base(":gfg/GFG"))
	
	fmt.Println("", filepath.Base(""))
	fmt.Println(".", filepath.Base("."))
	fmt.Println("/", filepath.Base("/"))
	fmt.Println("/.", filepath.Base("/."))
	fmt.Println("//", filepath.Base("//"))
	fmt.Println(":/", filepath.Base(":/"))
}

func extTest() {
	name := "A:/test:/123.doc"
	k := filepath.Ext(strings.ToLower(name))
	fmt.Println("key:", k)
}

func appendOne() {
	dir := "usr"
	subdir := "local"
	filename := "data.txt"
	fullpath := filepath.Join(dir, subdir, filename)
	fmt.Println("appendOne:", fullpath)
}

func appendTwo() {
	filename := "data.txt"
	fullpath := filepath.Join(string(filepath.Separator), filename)
	fmt.Println("appendTwo:", fullpath)
}

func appendThree() {
	parts := []string{"usr", "local", "data.txt"}
	fullpath := filepath.Join(parts...)
	fmt.Println("appendThree:", fullpath)
}

func absolutePath() {
	// 绝对路径
	fullpath1 := filepath.Join("/usr/local", "data.txt")
	fmt.Println("absolutePath:", fullpath1)
}

func relativePath() {
	// 相对路径
	fullpath2 := filepath.Join("src", "main.go")
	fmt.Println("relativePath:", fullpath2)
}

// 字符串头部处理
func urlProcess(url string) string {
	//判断是否以http://开头，返回布尔类型赋予result
	//HasPrefix()函数判断前缀
	result := strings.HasPrefix(url, "http://")
	fmt.Println("1result:= ", result)
	
	if !result {
		url = fmt.Sprintf("http://%s", url)
	}
	return url
}

// 字符串尾部处理
func pathProcess(path string) string {
	//HasSuffix()函数判断后缀
	result := strings.HasSuffix(path, "/")
	fmt.Println("2result:= ", result)
	
	if !result {
		path = fmt.Sprintf("%s/", path)
	}
	return path
}
